#include <WiFi.h>
#include <esp_now.h>

// 引脚定义
#define BUTTON_A_PIN 15
#define BUTTON_B_PIN 16
#define STATUS_LED 2

// 数据结构体（与接收端严格一致）
typedef struct {
  int xValueJpyA;    // X轴值
  int yValueJpyA;     
  int xValueJpyB;    
  int yValueJpyB;       
} JoystickData;
JoystickData joyData;

uint8_t receiverMac[] = {0x40,0xF5,0x20,0x58,0x68,0xFC};

// 死区过滤函数
int deadZoneFilter(int val, int center=2048, int deadZone=200) {
  return (abs(val - center) < deadZone) ? center : val;
}

void OnDataSent(const uint8_t *mac, esp_now_send_status_t status) {
  digitalWrite(STATUS_LED, (status == ESP_NOW_SEND_SUCCESS) ? HIGH : LOW);
}

void setup() {
  Serial.begin(115200);
  WiFi.mode(WIFI_STA);
  
  // 初始化按钮引脚
  pinMode(BUTTON_A_PIN, INPUT_PULLUP);
  pinMode(BUTTON_B_PIN, INPUT_PULLUP);
  pinMode(STATUS_LED, OUTPUT);

  if (esp_now_init() != ESP_OK) {
    Serial.println("ESP-NOW初始化失败");
    while(1); // 阻塞
  }

  // 修正后的对等节点配置
  esp_now_peer_info_t peerInfo = {
    .peer_addr = {0},       // 先初始化MAC地址
    .channel = 1,           // 信道
    .ifidx = WIFI_IF_STA,   // 最后初始化接口类型
    .encrypt = false
  };
  memcpy(peerInfo.peer_addr, receiverMac, 6);
  
  if (esp_now_add_peer(&peerInfo) != ESP_OK) {
    Serial.println("添加对等节点失败");
    while(1);
  }
  
  esp_now_register_send_cb(OnDataSent);
}

void loop() {
  // 读取原始数据
  int xJoyA = analogRead(34), yJoyA = analogRead(35);
  int xJoyB = analogRead(36), yJoyB = analogRead(32);
  
  // 数据处理
  joyData.xValueJpyA = map(deadZoneFilter(xJoyA), 0, 4095, -100, 100);
  joyData.yValueJpyA = map(deadZoneFilter(yJoyA), 0, 4095, -100, 100);
  joyData.xValueJpyB = map(deadZoneFilter(xJoyB), 0, 4095, -100, 100);
  joyData.yValueJpyB = map(deadZoneFilter(yJoyB), 0, 4095, -100, 100);

  // 发送数据
  esp_err_t result = esp_now_send(receiverMac, (uint8_t*)&joyData, sizeof(joyData));
  if (result != ESP_OK) {
    Serial.printf("发送失败，错误码：0x%X\n", result);
  }
  
  delay(20); // 50Hz发送频率
}
